package com.itheima.service.impl;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.StrUtil;
import com.itheima.common.CustomException;
import com.itheima.common.TokenHolder;
import com.itheima.dao.ShoppingCartMapper;
import com.itheima.pojo.ShoppingCart;
import com.itheima.service.ShoppingCardService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.lang.reflect.Array;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @author Administrator
 */
@Service
public class ShoppingCardServiceImpl implements ShoppingCardService {

    @Resource
    private ShoppingCartMapper shoppingCartMapper;



     private  static String userId =null;

    /**
     * 购物车列表
     *
     * @return
     */
    @Override
    public List<ShoppingCart> getList() {
        userId = TokenHolder.getCurrentId();

        return  shoppingCartMapper.selectList(userId);
    }

    /**
     * 删除购物车商品
     *
     * @param dishId
     * @param setMealId
     * @return
     */
    @Override
    public Boolean removeByDishIdOrSetMealId(String dishId, String setMealId) {

        int number = shoppingCartMapper.selectByDishIdOrSetMealId(dishId, setMealId,userId);
        if(number>1){
            int res = shoppingCartMapper.reduceNumber(dishId,setMealId);
            return res>0;
        }

        int i = shoppingCartMapper.deletedByDishIdOrSetMealId(dishId, setMealId);

        return i > 0;
    }

    /**
     * 添加到购物车
     *
     * @param shoppingCart
     * @return
     */
    @Override
    public Boolean addToCart(ShoppingCart shoppingCart) {

        Integer number = shoppingCartMapper.selectNumberByName(shoppingCart.getName(),userId);
        if(number!=null){
            int i = shoppingCartMapper.addNumber(shoppingCart.getName(),userId);
            return i>0;
        }

        String currentId = TokenHolder.getCurrentId();
        shoppingCart.setUserId(currentId);

        shoppingCart.setId(new Snowflake().nextIdStr());
        shoppingCart.setNumber(1);
        int i = shoppingCartMapper.addToCart(shoppingCart);

        return i > 0;


    }

    /**
     * 清空购物车
     * @return
     */
    @Override
    public Boolean removeAll() {
        userId = TokenHolder.getCurrentId();
        if (StrUtil.isEmpty(userId)) {
            throw new CustomException("请先登录");
        }
        int i = shoppingCartMapper.deleteAll(userId);
        return i > 0;
    }


}
